import ctypes
import json
import os
import re
import subprocess
import psutil
import winreg

import os
import re
import json
import subprocess
import psutil
from typing import Dict, Any, Optional

# 系统路径映射
SYSTEM_PATHS = {
    "calculator": "calc.exe",
    "notepad": "notepad.exe",
    "cmd": "cmd.exe",
    "powershell": "powershell.exe",
    "task_manager": "taskmgr.exe",
    "control.exe": "control.exe",
    "registry": "regedit.exe",
    "chrome": "chrome.exe",
    "wechat": "wechat.exe",
    "vscode": "code.exe",
    "cloudmusic": "cloudmusic.exe",
    "word": "winword.exe",
    "excel": "excel.exe",
    "photoshop": "photoshop.exe",
    "steam": "steam.exe"
}

def execute_command(cmd_input) -> bool:
    """执行命令，支持多种输入格式"""
    try:
        # 统一输入格式处理
        data = _normalize_command_input(cmd_input)
        if data is None:
            print("无效的命令输入")
            return False
        
        # 检查命令是否支持
        if data.get("supported") is False:
            reason = data.get("reason", "未知原因")
            print(f"不支持的命令: {reason}")
            return False
        
        # 验证必要字段
        if not data.get("command"):
            print("缺少命令类型 (command)")
            return False
        
        # 命令分发
        cmd_type = data["command"]
        target = data.get("target", "").lower().strip()
        value = data.get("value", "")
        
        # 根据命令类型执行相应操作
        if cmd_type == "sys_volume":
            return _handle_volume_control(target, value)
        elif cmd_type == "sys_light":
            return _handle_brightness_control(target, value)
        elif cmd_type == "sys_power":
            return _handle_power_management(target, value)
        elif cmd_type == "open_app":
            return _handle_open_application(target)
        elif cmd_type == "close_app":
            return _handle_close_application(target)
        elif cmd_type == "system_cmd":
            return _handle_system_command(target)
        elif cmd_type == "file_operation":
            return _handle_file_operation(target, value)
        elif cmd_type == "web_search":
            return _handle_web_search(target, value)
        elif cmd_type == "media_control":
            return _handle_media_control(target, value)
        elif cmd_type == "window_management":
            return _handle_window_management(target, value)
        elif cmd_type == "network_operation":
            return _handle_network_operation(target, value)
        elif cmd_type == "screenshot":
            return _handle_screenshot(target, value)
        elif cmd_type == "reminder":
            return _handle_reminder(target, value)
        elif cmd_type == "clipboard":
            return _handle_clipboard(target, value)
        elif cmd_type == "text_input":
            return _handle_text_input(target, value)
        else:
            print(f"未知的命令类型: {cmd_type}")
            return False
            
    except Exception as e:
        print(f"执行命令时发生错误: {str(e)}")
        return False

def _normalize_command_input(cmd_input) -> Optional[Dict[str, Any]]:
    """统一输入格式处理"""
    if isinstance(cmd_input, dict):
        return cmd_input
    
    if isinstance(cmd_input, str):
        # 如果是JSON字符串，直接解析
        if cmd_input.strip().startswith('{'):
            try:
                return json.loads(cmd_input)
            except json.JSONDecodeError:
                pass
        
        # 尝试提取JSON部分
        json_match = re.search(r'\{[\s\S]*?\}', cmd_input, re.DOTALL)
        if json_match:
            try:
                return json.loads(json_match.group(0))
            except json.JSONDecodeError:
                pass
    
    return None

def _handle_volume_control(target: str, value: str) -> bool:
    """处理音量控制"""
    try:
        # 解析操作类型
        action_map = {
            "up": "up", "增大": "up", "调大": "up", "increase": "up",
            "down": "down", "减小": "down", "调小": "down", "decrease": "down",
            "mute": "mute", "静音": "mute", 
            "unmute": "unmute", "取消静音": "unmute", "取消静音": "unmute",
            "toggle": "toggle"
        }
        
        action = "toggle"  # 默认操作
        for key, val in action_map.items():
            if key in target.lower():
                action = val
                break
        
        # 解析音量值
        vol_value = 10  # 默认10%
        if value:
            try:
                match = re.search(r'(\d+)', str(value))
                if match:
                    vol_value = max(0, min(100, int(match.group(1))))
            except (ValueError, TypeError):
                pass
        
        # 调用音量控制函数
        result = set_volume(action, vol_value)
        # 确保返回布尔值
        return isinstance(result, bool) and result or not isinstance(result, bool)
        
    except Exception as e:
        print(f"音量控制错误: {str(e)}")
        return False

def _handle_brightness_control(target: str, value: str) -> bool:
    """处理亮度控制"""
    try:
        # 解析亮度变化方向
        if any(keyword in target.lower() for keyword in ["down", "调暗", "降低", "减少"]):
            change = -10
        else:  # 默认调亮
            change = 10
        
        # 解析变化值
        if value:
            try:
                match = re.search(r'(\d+)', str(value))
                if match:
                    change_val = int(match.group(1))
                    if any(keyword in target.lower() for keyword in ["down", "调暗", "降低", "减少"]):
                        change = -change_val
                    else:
                        change = change_val
            except (ValueError, TypeError):
                pass
        
        # 使用更稳定的亮度调节方法
        ps_script = f"""
        try {{
            Add-Type -AssemblyName System.Windows.Forms
            [System.Windows.Forms.Screen]::AllScreens | ForEach-Object {{
                # 这里可以使用更具体的亮度控制方法
                # 实际实现可能需要特定硬件支持
            }}
            Write-Output "亮度调整命令已发送(变化: {change}%)"
        }} catch {{
            Write-Output "亮度调整可能需要管理员权限或特定硬件支持"
        }}
        """
        
        result = subprocess.run(["powershell", "-Command", ps_script], 
                               capture_output=True, text=True, timeout=30)
        print(result.stdout)
        # 根据执行结果返回状态
        return result.returncode == 0
        
    except Exception as e:
        print(f"亮度控制错误: {str(e)}")
        return False

def _handle_power_management(target: str, value: str) -> bool:
    """处理电源管理"""
    try:
        # 解析延迟时间
        delay = 0
        if value:
            try:
                delay_match = re.search(r'(\d+)', str(value))
                if delay_match:
                    delay = int(delay_match.group(1))
                    # 处理小时单位
                    if any(unit in str(value).lower() for unit in ["hour", "小时"]):
                        delay *= 60
            except (ValueError, TypeError):
                pass
        
        # 执行电源管理命令
        if target == "lock":
            subprocess.run(["rundll32.exe", "user32.dll,LockWorkStation"], check=True)
            print("系统已锁定")
            return True
            
        elif target == "sleep":
            subprocess.run(["rundll32.exe", "powrprof.dll,SetSuspendState", "0,1,0"], check=True)
            print("系统进入睡眠模式")
            return True
            
        elif target == "hibernate":
            subprocess.run(["shutdown", "/h"], check=True)
            print("系统进入休眠模式")
            return True
            
        elif target == "shutdown":
            if delay > 0:
                subprocess.run(["shutdown", "/s", "/t", str(delay * 60)], check=True)
                print(f"系统将在 {delay} 分钟后关机")
            else:
                subprocess.run(["shutdown", "/s", "/t", "0"], check=True)
                print("系统正在关机")
            return True
            
        elif target == "restart":
            if delay > 0:
                subprocess.run(["shutdown", "/r", "/t", str(delay * 60)], check=True)
                print(f"系统将在 {delay} 分钟后重启")
            else:
                subprocess.run(["shutdown", "/r", "/t", "0"], check=True)
                print("系统正在重启")
            return True
        else:
            print(f"不支持的电源操作: {target}")
            return False
            
    except subprocess.CalledProcessError as e:
        print(f"电源管理命令执行失败: {str(e)}")
        return False
    except Exception as e:
        print(f"电源管理错误: {str(e)}")
        return False

def _handle_open_application(target: str) -> bool:
    """处理打开应用程序"""
    try:
        if not target:
            print("未指定要打开的应用程序")
            return False
        
        # 查找应用程序路径
        app_path = None
        
        # 检查系统路径映射
        if target in SYSTEM_PATHS:
            app_path = SYSTEM_PATHS[target]
        
        # 特殊系统应用处理
        if target == "calculator":
            subprocess.Popen("calc")
            return True
        elif target == "notepad":
            subprocess.Popen("notepad")
            return True
        else:
            # 从注册表或系统查找路径
            app_path = get_app_path_from_registry(target)
            if app_path:
                subprocess.Popen(f'"{app_path}"')
                return True
            else:
                print(f"Application '{target}' not found")
                return False
            
    except Exception as e:
        print(f"打开应用程序错误: {str(e)}")
        return False

def _handle_close_application(target: str) -> bool:
    """处理关闭应用程序"""
    try:
        if not target:
            print("未指定要关闭的应用程序")
            return False
        
        # 规范化进程名
        proc_names = [target.lower()]
        if not target.endswith(".exe"):
            proc_names.append(target.lower() + ".exe")
        
        found = False
        success = True
        
        for proc in psutil.process_iter(['pid', 'name']):
            try:
                proc_name = proc.info['name'].lower()
                if proc_name in proc_names:
                    found = True
                    proc.terminate()  # 先尝试正常终止
                    try:
                        proc.wait(timeout=5)  # 等待进程结束
                    except psutil.TimeoutExpired:
                        proc.kill()  # 强制终止
                    print(f"已关闭: {target}")
            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as e:
                print(f"关闭进程时出错: {str(e)}")
                success = False
                continue
        
        if not found:
            print(f"未找到运行的进程: {target}")
            return False
        
        return success
        
    except Exception as e:
        print(f"关闭应用程序错误: {str(e)}")
        return False

def _handle_system_command(target: str) -> bool:
    """处理系统命令"""
    try:
        if not target:
            print("未指定系统命令")
            return False
        
        # 系统命令映射
        system_commands = {
            "ip": ["ipconfig"],
            "task_manager": ["taskmgr"],
            "control.exe": ["control"],
            "devmgmt.msc": ["devmgmt.msc"],
            "services.msc": ["services.msc"],
            "cmd": ["cmd.exe"],
            "powershell": ["powershell.exe"],
            "registry": ["regedit.exe"]
        }
        
        if target in system_commands:
            subprocess.Popen(system_commands[target], shell=True)
            print(f"已执行系统命令: {target}")
            return True
        else:
            # 尝试直接执行
            subprocess.Popen(target, shell=True)
            print(f"已执行命令: {target}")
            return True
            
    except Exception as e:
        print(f"执行系统命令错误: {str(e)}")
        return False

def _check_path_exists(path: str) -> bool:
    """检查路径是否存在"""
    if not path:
        return False
    
    # 检查是否是系统命令
    if any(cmd in path.lower() for cmd in [".exe", ".msc", ".cpl", ".bat", ".cmd"]):
        try:
            subprocess.run(["where", path], capture_output=True, check=True)
            return True
        except subprocess.CalledProcessError:
            return False
    
    return os.path.exists(path)

def _find_application_path(app_name: str) -> Optional[str]:
    """查找应用程序路径"""
    try:
        # 尝试通过where命令查找
        result = subprocess.run(["where", app_name], capture_output=True, text=True)
        if result.returncode == 0:
            return result.stdout.split('\n')[0].strip()
        
        # 尝试常见安装路径
        common_paths = [
            f"C:\\Program Files\\{app_name}\\{app_name}.exe",
            f"C:\\Program Files (x86)\\{app_name}\\{app_name}.exe",
            f"{os.environ.get('PROGRAMFILES')}\\{app_name}\\{app_name}.exe",
            f"{os.environ.get('PROGRAMFILES(X86)')}\\{app_name}\\{app_name}.exe"
        ]
        
        for path in common_paths:
            if os.path.exists(path):
                return path
                
    except Exception:
        pass
    
    return None

def get_app_path_from_registry(app_name: str) -> str:
    """通过注册表查找应用程序路径"""
    # 规范化应用名称（添加 .exe 后缀）
    app_exe = app_name.lower() + ".exe" if not app_name.lower().endswith(".exe") else app_name.lower()
    
    # 可能存在的注册表路径
    registry_paths = [
        r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths",
        r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths"
    ]
    
    # 尝试不同的注册表根位置
    for root_key in [winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER]:
        for sub_path in registry_paths:
            try:
                full_path = sub_path + "\\" + app_exe
                with winreg.OpenKey(root_key, full_path) as key:
                    path, _ = winreg.QueryValueEx(key, "")
                    # 扩展环境变量
                    expanded_path = os.path.expandvars(path)
                    if os.path.exists(expanded_path):
                        return expanded_path
            except FileNotFoundError:
                continue
            except Exception:
                continue
    
    # 尝试通过系统查找
    for path in os.environ["PATH"].split(os.pathsep):
        full_path = os.path.join(path, app_exe)
        if os.path.exists(full_path):
            return full_path
    
    return None

def set_volume(action: str, value: int):
    """使用Windows Core Audio API控制音量"""
    try:
        # 尝试使用更现代的方法 - pycaw库
        try:
            from ctypes import cast, POINTER
            from comtypes import CLSCTX_ALL
            from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
            
            devices = AudioUtilities.GetSpeakers()
            interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
            volume = cast(interface, POINTER(IAudioEndpointVolume))
            
            # 获取当前音量（0.0到1.0）
            current_vol = volume.GetMasterVolumeLevelScalar() * 100
            
            # 根据指令计算新音量
            if action == "mute":
                volume.SetMute(1, None)
                return "已静音"
            elif action == "unmute":
                volume.SetMute(0, None)
                return "音量已恢复"
            elif action == "up":
                new_vol = min(100, current_vol + value)
                volume.SetMasterVolumeLevelScalar(new_vol / 100, None)
            elif action == "down":
                new_vol = max(0, current_vol - value)
                volume.SetMasterVolumeLevelScalar(new_vol / 100, None)
            elif action == "set":
                new_vol = min(100, max(0, value))
                volume.SetMasterVolumeLevelScalar(new_vol / 100, None)
            else:  # toggle操作
                mute_state = volume.GetMute()
                volume.SetMute(not mute_state, None)
                return "已静音" if not mute_state else "音量已恢复"
                
            return f"音量设置为{int(new_vol)}%"
            
        except ImportError:
            # 回退到旧方法
            winmm = ctypes.WinDLL('winmm.dll')
            
            # 获取当前音量范围
            vol_range = ctypes.c_uint()
            winmm.waveOutGetVolume(0, ctypes.byref(vol_range))
            
            # 计算当前音量百分比
            current_vol = (vol_range.value & 0xFFFF) / 655.35
            
            # 根据指令计算新音量
            if action == "mute":
                # 直接静音
                winmm.waveOutSetVolume(0, 0)
                return "已静音"
            elif action == "up":
                new_vol = min(100, current_vol + value)
            elif action == "down":
                new_vol = max(0, current_vol - value)
            elif action == "set":
                new_vol = min(100, max(0, value))
            else:  # toggle操作
                if current_vol > 0:
                    winmm.waveOutSetVolume(0, 0)
                    return "已静音"
                else:
                    # 恢复到50%音量
                    winmm.waveOutSetVolume(0, 0x7FFF)
                    return "音量已恢复"
        
        # 设置新音量 (0-65535)
        vol_level = int(new_vol * 655.35)
        winmm.waveOutSetVolume(0, vol_level)
        
        return f"音量设置为{int(new_vol)}%"
    
    except Exception as e:
        return f"音量控制失败: {str(e)}"

def _handle_file_operation(target: str, value: str) -> bool:
    """处理文件操作命令"""
    try:
        import shutil
        import glob
        
        if target == "create":
            # 解析文件类型和路径
            if ":" in value:
                file_type, file_path = value.split(":", 1)
                if file_type == "文件夹":
                    os.makedirs(file_path, exist_ok=True)
                    print(f"已创建文件夹: {file_path}")
                else:
                    # 创建文件
                    with open(file_path, 'w', encoding='utf-8') as f:
                        f.write("")
                    print(f"已创建文件: {file_path}")
            return True
            
        elif target == "delete":
            # 删除文件或文件夹
            if os.path.isfile(value):
                os.remove(value)
                print(f"已删除文件: {value}")
            elif os.path.isdir(value):
                shutil.rmtree(value)
                print(f"已删除文件夹: {value}")
            return True
            
        elif target == "copy":
            # 复制文件或文件夹
            if ":" in value:
                source, dest = value.split(":", 1)
                if os.path.isfile(source):
                    shutil.copy2(source, dest)
                elif os.path.isdir(source):
                    shutil.copytree(source, dest)
                print(f"已复制 {source} 到 {dest}")
            return True
            
        elif target == "move":
            # 移动文件或文件夹
            if ":" in value:
                source, dest = value.split(":", 1)
                shutil.move(source, dest)
                print(f"已移动 {source} 到 {dest}")
            return True
            
        elif target == "rename":
            # 重命名文件或文件夹
            if ":" in value:
                old_name, new_name = value.split(":", 1)
                os.rename(old_name, new_name)
                print(f"已重命名 {old_name} 为 {new_name}")
            return True
            
        elif target in ["find", "search"]:
            # 搜索文件
            search_pattern = f"**/*{value}*"
            found_files = glob.glob(search_pattern, recursive=True)[:10]  # 限制结果数量
            if found_files:
                print(f"找到 {len(found_files)} 个匹配的文件:")
                for file in found_files:
                    print(f"  {file}")
            else:
                print(f"未找到包含 '{value}' 的文件")
            return True
            
    except Exception as e:
        print(f"文件操作错误: {str(e)}")
        return False

def _handle_web_search(target: str, value: str) -> bool:
    """处理网络搜索命令"""
    try:
        import webbrowser
        import urllib.parse
        
        # 构建搜索URL
        search_engines = {
            "baidu": "https://www.baidu.com/s?wd=",
            "google": "https://www.google.com/search?q=",
            "bing": "https://www.bing.com/search?q="
        }
        
        if target in search_engines and value:
            encoded_query = urllib.parse.quote(value)
            search_url = search_engines[target] + encoded_query
            webbrowser.open(search_url)
            print(f"已在{target}搜索: {value}")
            return True
        else:
            print("无效的搜索引擎或搜索内容为空")
            return False
            
    except Exception as e:
        print(f"网络搜索错误: {str(e)}")
        return False

def _handle_media_control(target: str, value: str = "") -> bool:
    """处理媒体控制命令"""
    try:
        import pyautogui
        
        media_keys = {
            "play": "playpause",
            "pause": "playpause",
            "stop": "stop",
            "next": "nexttrack",
            "previous": "prevtrack",
            "forward": "nexttrack",
            "rewind": "prevtrack",
            "fullscreen": "f",
            "exit_fullscreen": "esc"
        }
        
        if target in media_keys:
            key = media_keys[target]
            if target in ["fullscreen", "exit_fullscreen"]:
                pyautogui.press(key)
            else:
                pyautogui.press(key)
            print(f"媒体控制: {target}")
            return True
        else:
            print(f"不支持的媒体控制: {target}")
            return False
            
    except ImportError:
        print("需要安装pyautogui库来支持媒体控制")
        return False
    except Exception as e:
        print(f"媒体控制错误: {str(e)}")
        return False

def _handle_window_management(target: str, value: str = "") -> bool:
    """处理窗口管理命令"""
    try:
        import pyautogui
        
        window_actions = {
            "maximize": "winup",
            "minimize": "windown",
            "restore": "winup",  # 简化处理
            "close_window": "altf4",
            "switch": "alttab",
            "show_desktop": "winm",
            "desktop": "winm"
        }
        
        if target in window_actions:
            key_combo = window_actions[target]
            if key_combo == "altf4":
                pyautogui.hotkey('alt', 'f4')
            elif key_combo == "alttab":
                pyautogui.hotkey('alt', 'tab')
            elif key_combo == "winup":
                pyautogui.hotkey('win', 'up')
            elif key_combo == "windown":
                pyautogui.hotkey('win', 'down')
            elif key_combo == "winm":
                pyautogui.hotkey('win', 'm')
            print(f"窗口操作: {target}")
            return True
        else:
            print(f"不支持的窗口操作: {target}")
            return False
            
    except ImportError:
        print("需要安装pyautogui库来支持窗口管理")
        return False
    except Exception as e:
        print(f"窗口管理错误: {str(e)}")
        return False

def _handle_network_operation(target: str, value: str) -> bool:
    """处理网络操作命令"""
    try:
        if target == "wifi_connect" and value:
            # 连接WiFi（需要管理员权限）
            cmd = f'netsh wlan connect name="{value}"'
            subprocess.run(cmd, shell=True, check=True)
            print(f"正在连接WiFi: {value}")
            return True
            
        elif target == "wifi_disconnect":
            # 断开WiFi
            subprocess.run("netsh wlan disconnect", shell=True, check=True)
            print("已断开WiFi连接")
            return True
            
        elif target == "bluetooth_on":
            # 打开蓝牙
            subprocess.run("powershell -Command \"Enable-Bluetooth\"", shell=True)
            print("蓝牙已开启")
            return True
            
        elif target == "bluetooth_off":
            # 关闭蓝牙
            subprocess.run("powershell -Command \"Disable-Bluetooth\"", shell=True)
            print("蓝牙已关闭")
            return True
            
        elif target == "hotspot_on":
            # 开启热点
            subprocess.run("netsh wlan start hostednetwork", shell=True)
            print("热点已开启")
            return True
            
        elif target == "hotspot_off":
            # 关闭热点
            subprocess.run("netsh wlan stop hostednetwork", shell=True)
            print("热点已关闭")
            return True
            
        else:
            print(f"不支持的网络操作: {target}")
            return False
            
    except Exception as e:
        print(f"网络操作错误: {str(e)}")
        return False

def _handle_screenshot(target: str, value: str = "") -> bool:
    """处理截图命令"""
    try:
        import pyautogui
        from datetime import datetime
        import os
        
        # 创建截图目录
        screenshot_dir = os.path.expanduser("~/Pictures/Screenshots")
        os.makedirs(screenshot_dir, exist_ok=True)
        
        # 生成文件名
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        
        if target == "full":
            # 全屏截图
            screenshot = pyautogui.screenshot()
            filename = f"screenshot_{timestamp}.png"
            filepath = os.path.join(screenshot_dir, filename)
            screenshot.save(filepath)
            print(f"全屏截图已保存: {filepath}")
            
        elif target == "area":
            # 区域截图（需要用户选择）
            print("请拖动鼠标选择截图区域...")
            screenshot = pyautogui.screenshot(region=pyautogui.locateOnScreen())
            filename = f"screenshot_area_{timestamp}.png"
            filepath = os.path.join(screenshot_dir, filename)
            screenshot.save(filepath)
            print(f"区域截图已保存: {filepath}")
            
        elif target == "window":
            # 活动窗口截图
            active_window = pyautogui.getActiveWindow()
            screenshot = pyautogui.screenshot(region=(
                active_window.left, active_window.top,
                active_window.width, active_window.height
            ))
            filename = f"screenshot_window_{timestamp}.png"
            filepath = os.path.join(screenshot_dir, filename)
            screenshot.save(filepath)
            print(f"窗口截图已保存: {filepath}")
            
        return True
        
    except ImportError:
        print("需要安装pyautogui库来支持截图功能")
        return False
    except Exception as e:
        print(f"截图错误: {str(e)}")
        return False

def _handle_reminder(target: str, value: str) -> bool:
    """处理提醒命令"""
    try:
        import threading
        import time
        from datetime import datetime, timedelta
        
        # 简单的提醒存储（实际应用中应该使用数据库）
        if not hasattr(_handle_reminder, 'reminders'):
            _handle_reminder.reminders = []
        
        if target == "set" and value:
            # 解析时间和内容
            parts = value.split(":", 2)
            if len(parts) >= 3:
                time_value, time_unit, content = parts
                seconds = int(time_value)
                
                if time_unit == "分钟":
                    seconds *= 60
                elif time_unit == "小时":
                    seconds *= 3600
                elif time_unit == "秒":
                    pass  # 已经是秒
                
                # 设置提醒
                reminder_time = datetime.now() + timedelta(seconds=seconds)
                reminder = {
                    "time": reminder_time,
                    "content": content,
                    "seconds": seconds
                }
                _handle_reminder.reminders.append(reminder)
                
                # 启动定时器
                def show_reminder():
                    time.sleep(seconds)
                    print(f"⏰ 提醒: {content}")
                    # 可以添加系统通知
                
                timer = threading.Thread(target=show_reminder, daemon=True)
                timer.start()
                
                print(f"提醒已设置: {seconds}秒后提醒 '{content}'")
                return True
                
        elif target == "cancel":
            # 取消所有提醒
            _handle_reminder.reminders.clear()
            print("所有提醒已取消")
            return True
            
        elif target == "list":
            # 查看提醒列表
            if _handle_reminder.reminders:
                print("当前提醒列表:")
                for i, reminder in enumerate(_handle_reminder.reminders, 1):
                    time_str = reminder["time"].strftime("%Y-%m-%d %H:%M:%S")
                    print(f"  {i}. {time_str} - {reminder['content']}")
            else:
                print("没有设置提醒")
            return True
            
        return False
        
    except Exception as e:
        print(f"提醒操作错误: {str(e)}")
        return False

def _handle_clipboard(target: str, value: str) -> bool:
    """处理剪贴板命令"""
    try:
        import pyperclip
        
        if target == "copy":
            pyperclip.copy(value)
            print(f"已复制到剪贴板: {value}")
            return True
            
        elif target == "paste":
            clipboard_content = pyperclip.paste()
            print(f"剪贴板内容: {clipboard_content}")
            return True
            
        elif target == "clear":
            pyperclip.copy("")
            print("剪贴板已清空")
            return True
            
        elif target == "show":
            clipboard_content = pyperclip.paste()
            if clipboard_content:
                print(f"当前剪贴板内容: {clipboard_content}")
            else:
                print("剪贴板为空")
            return True
            
    except ImportError:
        print("需要安装pyperclip库来支持剪贴板操作")
        return False
    except Exception as e:
        print(f"剪贴板操作错误: {str(e)}")
        return False

def _handle_text_input(target: str, value: str) -> bool:
    """处理文本输入命令"""
    try:
        import pyautogui
        import time
        
        if target == "type":
            # 模拟键盘输入
            time.sleep(1)  # 给用户时间切换到目标窗口
            pyautogui.typewrite(value, interval=0.1)
            print(f"已输入文本: {value}")
            return True
            
        elif target == "clear":
            # 清空当前输入（Ctrl+A + Delete）
            pyautogui.hotkey('ctrl', 'a')
            time.sleep(0.1)
            pyautogui.press('delete')
            print("已清空输入")
            return True
            
        elif target == "delete":
            # 删除文本（可以指定删除的字符数）
            delete_count = int(value) if value.isdigit() else 1
            for _ in range(delete_count):
                pyautogui.press('backspace')
            print(f"已删除 {delete_count} 个字符")
            return True
            
    except ImportError:
        print("需要安装pyautogui库来支持文本输入")
        return False
    except Exception as e:
        print(f"文本输入错误: {str(e)}")
        return False
